package me.xuym.crawler.t66y;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.network.HttpClient;
import com.cbs.java.component.network.Request;
import com.cbs.java.component.network.Response;
import com.cbs.java.component.network.decoder.TextDecoder;
import me.xuym.crawler.Loader;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by broche on 11/09/2017.
 */
public class T66yLoader extends Loader<String> {
    private HttpClient httpClient;

    public T66yLoader(Application application) {
        super(application);

        HttpClient.Builder builder = new HttpClient.Builder();
        String proxyHost = "cephei.xuym.me";
        int proxyPort = 1010;
        builder.getOkBuilder().proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)));

        if (proxyHost != null && !proxyHost.equals("")) {
            builder.getOkBuilder().proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort)));
        }
        httpClient = builder.build();
    }

    @Override
    protected String onLoad() throws Exception {
        StringBuilder stringBuilder = new StringBuilder();

        Request request = new Request("http://t66y.com/index.php").setDecoder(new TextDecoder("gbk"));
        Response response = httpClient.sendSync(request);
        String indexPage = (String) response.getResult();

        stringBuilder.append(getPage(indexPage, "<a href=\"([^\"]*)\">亞洲無碼原創區</a>"));
        stringBuilder.append(getPage(indexPage, "<a href=\"([^\"]*)\">亞洲有碼原創區</a>"));

        return stringBuilder.toString();
    }

    private String getPage(String content, String patternStr) throws IOException {
        String result = "";

        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            String url = matcher.group(1);
            Request request = new Request("http://t66y.com/" + url).setDecoder(new TextDecoder("gbk"));
            Response response = httpClient.sendSync(request);
            result = (String) response.getResult();
        }
        return result;
    }
}
